<?php


namespace app\home\controller;


use app\base\BaseController;
use think\facade\Db;

/**
 * Class SaleProCount
 * @package app\home\controller
 * 销售产品汇总
 */
class SaleProCount extends BaseController
{
    public function index()
    {
        if (request()->isAjax()) {
            $param=$this->param;
            $where[]=['ord.status','=',2];
            $where[]=['or.type','=','销售发货'];
            if (isset($param['bar_code'])&&$param['bar_code']){
                $where[]=['md.bar_code','like','%'.$param['bar_code']];
            }
            if (isset($param['mdName'])&&$param['mdName']){
                $where[]=['md.name','like','%'.$param['mdName'].'%'];
            }
            if (isset($param['orderDate'])&&$param['orderDate']){
                $dates=explode('~',$param['orderDate']);
                $where[]=['or.outTime','between',$dates];
            }
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
           $list= Db::name('out_receipt_detail')->alias('ord')
                ->leftJoin('out_receipt or','or.id=ord.out_receipt_id')
                ->leftJoin('purveyor p ','p.id=or.punter_id')
                ->leftJoin('material_dossier md','md.id=ord.material_dossier_id')
                ->where($where)
                ->field('ord.material_dossier_id,ord.out_receipt_id,
                p.name as pName,md.name as mdName,md.bar_code,md.specs,md.unit,
                sum(ord.num) as saleNum')
                ->group('material_dossier_id')
                ->paginate($rows)->each(function ($item){
                    $tuihuo=Db::name('in_receipt_detail')->alias('ird')
                        ->leftJoin('in_receipt ir','ir.id=ird.in_receipt_id')
                        ->where('ird.material_dossier_id',$item['material_dossier_id'])
                        ->where('ird.status','2')
                        ->where('ir.type','销售退货')->sum('num');
                    $item['finalNum']=$item['saleNum']-$tuihuo;
                    return $item;
               });
            return table_assign(0, '', $list);
        }
        return view();
}
}